<!--查询弹窗-->
<template>
    <a-modal class="search-wrapper-box" :visible="visible" title="查询" @cancel="cancel" width="1000px">
        <div class="content-box">
            <div class="right-box">
                <a-row class="condition" :gutter="[8,0]" style="margin-right:0px; height:460px;">
                    <div>
                        <!--搜索条件-->
                        <slot name="searchConditions"></slot>
                    </div>
                </a-row>
            </div>
        </div>
        <template slot="footer">
            <div>
                <!-- <div style="float:left">
                    <a-checkbox :checked="planActive == defaultPlanActive?true:false" @change="inPagePlanSave">
                        下次以此方案进入
                    </a-checkbox>
                </div> -->
                <a-button type="primary" @click="handlerSearchTemp">{{type=='pancun'?'确认':'查询'}}</a-button>
                <a-button @click="cancel" class="margin-left-10">取消</a-button>
            </div>
        </template>
        <a-modal :title="nowPlanType==1?'保存为另一个方案':'修改方案标题'" :visible="saveASVisible" width="400px" centered @cancel="saveAsPlanClose">
            <a-input v-model.trim="saveAsName" placeholder="请输入查询方案名称"></a-input>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="saveAsPlanSubmit(1)">确定</a-button>
                    <a-button @click="saveAsPlanClose" class="margin-left-10">取消</a-button>
                </div>
            </template>
        </a-modal>
    </a-modal>
</template>
<script>

import { save, remove, myplan, systemplan } from '@/api/erp/reportProgramme';
import FormDatePickerGroup from '@/components/Form/FormDatePickerGroup';
import FormSearchGroup from '@/components/Form/FormSearchGroup';
import searchArchives from '@/components/OrderDynamicForm/searchArchives'
import searchArchivesName from '@/components/OrderDynamicForm/searchArchivesName'
import moment from "moment";


import { remove as financeRemove, getList as financeList } from '@/api/finance/accountingSearch';//财务查询方案

//拖动
import Sortable from 'sortablejs';

export default {
    components: {
        FormDatePickerGroup,    //日期
        FormSearchGroup,        //搜索选择
        searchArchives,         //物料
        searchArchivesName,
    },
    props: {
        type: { //方案类型
            type: String,
            default: 1
        },
        componentType: { //是否是统计还是明细 1:明细 2:统计
            type: Number,
            default: 1
        },
        businessType: { //生产领退补的类型区分
            type: Number
        }
    },
    data() {
        return {
            visible: false,
            planActive: 0,//当前选中的方案
            columns: [],
            beginDate: new Date().getFullYear() + '-' + '1',
            endDate: moment().format('YYYY-MM-DD'),
            columnsDetail: [
                {
                    title: '排序',
                    dataIndex: "sort",
                    key: 'sort',
                    scopedSlots: { customRender: 'sort' },
                    width: 50,
                    align: 'center'
                },
                {
                    title: '字段名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '字段类型',
                    dataIndex: 'columnType',
                    key: 'columnType',
                },
                {
                    title: '字段来源',
                    dataIndex: 'fieldSource',
                    key: 'fieldSource',
                },
                {
                    title: '列宽',
                    dataIndex: 'columnWidth',
                    key: 'columnWidth',
                    scopedSlots: { customRender: 'columnWidth' },
                },
                {
                    title: '是否显示',
                    dataIndex: 'onShow',
                    key: 'onShow',
                    align: 'center',
                    scopedSlots: { customRender: 'onShow' },
                },
                {
                    title: '查询条件',
                    dataIndex: 'onSearch',
                    key: 'onSearch',
                    align: 'center',
                    scopedSlots: { customRender: 'onSearch' },
                },
                {
                    title: '汇总/合计',
                    dataIndex: 'onSummary',
                    key: 'onSummary',
                    align: 'center',
                    scopedSlots: { customRender: 'onSummary' },
                }
            ],
            columnsStaic: [
                {
                    title: '排序',
                    dataIndex: "sort",
                    key: 'sort',
                    scopedSlots: { customRender: 'sort' },
                    width: 50,
                    align: 'center'
                },
                {
                    title: '字段名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '字段类型',
                    dataIndex: 'columnType',
                    key: 'columnType',
                },
                {
                    title: '字段来源',
                    dataIndex: 'fieldSource',
                    key: 'fieldSource',
                },
                {
                    title: '列宽',
                    dataIndex: 'columnWidth',
                    key: 'columnWidth',
                    scopedSlots: { customRender: 'columnWidth' },
                },
                {
                    title: '查询条件',
                    dataIndex: 'onSearch',
                    key: 'onSearch',
                    align: 'center',
                    scopedSlots: { customRender: 'onSearch' },
                },
                {
                    title: '分组',
                    dataIndex: 'onGroup',
                    key: 'onGroup',
                    align: 'center',
                    scopedSlots: { customRender: 'onGroup' },
                },
                {
                    title: '汇总/合计',
                    dataIndex: 'onSummary',
                    key: 'onSummary',
                    align: 'center',
                    scopedSlots: { customRender: 'onSummary' },
                },
            ],
            dataSource: [],         //方案动态数据
            saveAsName: '',         //另存名称
            saveASVisible: false,   //另存名字弹窗
            myPlanList: [],         //个人自定义方案

            nowPlanData: [],        //当前显示数据
            nowPlanType: null,      //修改还是另存 //type==1新增，type==2改名
            activeKey: '1',



            //物料
            maskArchives: false,
            maskArchivesName: false,
            zIndex: 5,
            inputType: null,
            beginCode: null,
            endCode: null,
            inventoryName: null,

            //默认方案
            inPlanChecked: false,
            defaultPlanActive: null,
            inventoryDomTop: 0,
        }
    },
    created() {
        //获取系统方案
        // this.getSystemplan();
        //获取自定义方案列表
        // this.getMyselfPlan();
    },
    mounted() {
        // document.addEventListener('click', (e) => {
        //     //获取弹出表格对象
        //     // if (this.tableShow && this.boxId != null) {
        //     const userCon = document.getElementById('inventoryCode' + this.componentType);
        //     const userConName = document.getElementById('inventoryName' + this.componentType);

        //     console.log(userCon);
        //     //判断表格对象中是否包含点击对象
        //     if (userCon && !userCon.contains(e.target)) {
        //         this.archivesVisible = false
        //     }
        //     // }

        //     if (userConName && !userConName.contains(e.target)) {
        //         this.archivesVisibleName = false
        //     }

        // })
        // var _this = this;
        // window.onresize = () => {
        //     _this.archivesVisible = false
        //     _this.archivesVisibleName = false
        // }
    },
    wthch: {
        beginCode(val) {
            this.beginCode = val;
        },
        endCode(val) {
            this.endCode = val;
        },
        inventoryName(val) {
            this.inventoryName = val;
        }
    },
    methods: {
        moment,
        showModel() {
            this.visible = true;
            this.activeKey = '1';
        },
        cancel() {
            this.visible = false;
        },
        handlerSearch() {
            //保存并查询
            this.savePlan();//先保存，在去搜索
            setTimeout(() => {
                this.handlerSearchTemp();
            }, 120)
        },
        handlerSearchTemp() {
            //仅查询
            if (this.planActive == 0) {
                //默认方案查询
                this.nowPlanData.isDefaultPlan = true;//是否是默认方案的查询
                this.$emit('searchPlan', this.nowPlanData)
            } else {
                this.nowPlanData.isDefaultPlan = false;
                this.$emit('searchPlan', this.nowPlanData)
            }
        },
        changePlane(data) {
            //点击自定方案事件
            this.nowPlanData = data;//当前显示数据
            this.planActive = data.id;
            this.activeKey = '1';
            this.saveAsName = data.name;

            //给输入框中植入值
            this.$emit('setWarpperData', data);
        },
        callback(e) {
            this.activeKey = e;
            if (this.dataSource && this.dataSource.length > 0 && e == 2) {
                this.$nextTick(() => {
                    this.drag();
                })
            }
        },
        //保存方案
        savePlan(t) {
            let backData = { name: this.saveAsName, id: this.planActive, saveType: 2 }
            this.$emit('savePlan', backData);
        },
        //另存方案
        saveAsPlanShow(type) {
            this.nowPlanType = type;
            this.saveASVisible = true;
            this.saveAsName = type == 2 ? this.nowPlanData.name : '';
        },
        //确定另存方案
        saveAsPlanSubmit() { //type==1新增，type==2改名
            let type = this.nowPlanType;
            let name = this.saveAsName;
            if (name == null || name == '') {
                this.$message.warning('请输入查询方案名称', 1);
                return;
            } else {

                let backData = { name: this.saveAsName, saveType: type }
                if (type == 2) {
                    backData.id = this.planActive
                } else {
                    backData.id = null;
                }

                this.$emit('savePlan', backData);
                // this.saveASVisible = false;
                // this.saveAsName = '';
            }
        },
        //取消另存方案
        saveAsPlanClose() {
            this.saveASVisible = false;
        },
        //删除方案
        removePlan() {
            let _this = this;
            this.$confirm({
                title: "提示",
                content: (
                    <span>
                        是否确认删除{_this.nowPlanData.name}?
                    </span>
                ),
                onOk() {
                    financeRemove({ id: _this.nowPlanData.id }).then((response) => {
                        if (response.code === 200) {
                            _this.$message.success('删除成功');

                            //如果删除的是默认进入的方案
                            // let planchecked = localStorage.getItem(_this.reportCode);
                            // console.log(Number(planchecked) == _this.planActive)
                            // if (Number(planchecked) == _this.planActive) {
                            //     localStorage.setItem(_this.reportCode, 0);
                            // }

                            // _this.getSystemplan();
                            _this.getMyselfPlan();
                            // _this.$emit('newPlan');//刷新父组件数据

                        } else {
                            // _this.$message.warning(response.message);
                        }
                    }).catch((e) => {
                        // _this.$message.error('请求出错', 1)
                    })
                },
                onCancel() { },
            });
        },
        getSystemplan() {
            //点击默认方案
            this.planActive = 0;
            this.$emit('stystemSearch');
        },
        getMyselfPlan() {
            //获取个人方案列表
            financeList({ type: this.type }).then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.myPlanList = res.data;
                }
            }).catch((e) => {
                // this.$message.error('请求出错', 1)
            })
        },
        //下拉选择
        formatSelectJsonVal(val) {
            let thisVal = JSON.parse(val);
            let backVal = [];
            if (thisVal && thisVal != '' && thisVal != null) {
                thisVal.forEach((item, index) => {
                    backVal.push(item);
                });
            }
            return backVal;
        },
        //除文本外的form表单赋值
        handleChange(parameter1, parameter2, code, type) {
            // console.log(parameter1, parameter2, code, type);
            if (type == '下拉选择') {
                this.dataSource.forEach(item => {
                    if (item.code == code) {
                        item.value = parameter1;
                    }
                });
            } else if (type == '日期') {
                this.dataSource.forEach(item => {
                    if (item.code == code) {
                        item.value = parameter2;
                    }
                });
            }
        },
        //是否字段设计
        onChangeShow(e, record) {
            // console.log(this.dataSource, record, e)
            this.dataSource.forEach(item => {
                if (item.code == record.code) {
                    item.onShow = e.target.checked;
                }
            });
        },
        //是否搜索&是否显示
        onChangeSearch(e, record) {
            // console.log(this.dataSource, record, e)
            this.dataSource.forEach(item => {
                if (item.code == record.code) {
                    item.onSearch = e.target.checked;
                }
            });
        },
        //是否聚合
        onChangeGroup(e, record, t) {
            // console.log(this.dataSource, record, e)
            if (t == 'onGroup') {
                this.dataSource.forEach(item => {
                    if (item.code == record.code) {
                        item.onGroup = e.target.checked;
                        item.onSummary = false;
                    }
                });
            } else {
                this.dataSource.forEach(item => {
                    if (item.code == record.code) {
                        item.onSummary = e.target.checked;
                        item.onGroup = false;
                    }
                });
            }
        },
        //列宽
        onChangeWidth(e, record) {
            console.log(e.target.value)
            this.dataSource.forEach(item => {
                if (item.code == record.code) {
                    item.columnWidth = Number(e.target.value);
                }
            });
        },
        //日期修改回调
        handleDate(d, code) {
            console.log(d, code);
            this.dataSource.forEach(plan => {
                if (plan.code == code) {
                    this.$set(plan, 'rangDateVal', d)
                }
            })
        },



        //下拉搜索赋值=-----------------------------------
        setValue(data) {
            console.log(data);
            const { dataSource } = this;
            for (let i = 0; i < dataSource.length; i++) {
                if (dataSource[i].code == data.codesName) {
                    this.$set(dataSource[i], 'value', data.name)
                }

            }
            Object.assign(this.dataSource, dataSource)
        },
        handleSearch(n) {
            console.log(n);
            this.$refs[`${n}`][0].showModal();
        },

        //物料选择范围-----------------------------------
        checkArchives(data) {
            this.maskArchives = false;
            this.maskArchivesName = false;
            //返回值处理
            const { dataSource } = this;
            if (data[1] == 1) {
                //起始值
                this.beginCode = data[0][0].inventoryCode;
            }
            if (data[1] == 2) {
                //起始值
                this.endCode = data[0][0].inventoryCode;
            }

            for (let i = 0; i < dataSource.length; i++) {
                if (data[1] == 3) {
                    console.log(111111)
                    //物料编码名称
                    if (dataSource[i].code == 'inventoryId') {
                        this.$set(dataSource[i], 'value', data[0][0].inventoryName);
                        console.log('物料名称', data[0][0].inventoryName)
                        this.inventoryName = data[0][0].inventoryName;
                    }
                } else {
                    if (dataSource[i].code == 'inventoryCode') {
                        this.$set(dataSource[i], 'rangDateVal', ["物料编码范围", [this.beginCode, this.endCode]])
                    }
                }
            }
            Object.assign(this.dataSource, dataSource)
        },
        handlInputArchives(type, ref) {
            // console.log(this.$refs.searchArchivesRef,this.inputType)

            console.log()

            document.getElementsByClassName('ant-modal-content')[0].style.transform = 'none';

            this.inputType = type;
            if (type == 1 || type == 2) {
                this.maskArchives = true;
                this.zIndex = 1;
            } else {
                this.zIndex = 5;
                this.maskArchivesName = true;
            }
            //获取位置
            console.log(this.$refs[`${ref}`][0].parentNode.offsetTop);
            let loc = this.$refs[`${ref}`][0].getBoundingClientRect();
            this.inventoryDomTop = Math.abs(loc.top);
        },
        //关闭物料档案弹窗
        handlCloseArchives() {
            const { dataSource } = this;
            document.getElementsByClassName('ant-modal-content')[0].style.transform = 'translate(0px, 0px)';

            if (this.inputType == 1 || this.inputType == 2) {
                this.maskArchives = false;
                this.$refs.searchArchivesRef[0].closeModel();
                for (let i = 0; i < dataSource.length; i++) {
                    if (dataSource[i].code == 'inventoryCode') {
                        this.$set(dataSource[i], 'rangDateVal', ["物料编码范围", [this.beginCode, this.endCode]])
                    }
                }
                Object.assign(this.dataSource, dataSource)
            } else {
                this.maskArchivesName = false;
                this.$refs.searchArchivesRefName[0].closeModel();
                for (let i = 0; i < dataSource.length; i++) {
                    if (dataSource[i].code == 'inventoryId') {
                        this.$set(dataSource[i], 'value', this.inventoryName);
                    }
                }
            }
        },
        handleArchiveChange() {
            //物料编码搜索
            console.log(this.inputType)
            if (this.inputType == 1) {
                this.inputVal = this.beginCode;
            } else {
                this.inputVal = this.endCode;
            }
            this.$refs.searchArchivesRef[0].getData(1);
            this.$refs.searchArchivesRef[0].inputVal = this.inputVal;
        },
        handleNameChange() {
            //物料名称搜索
            // this.$refs.searchArchivesRefName[0].getData(this.inventoryName);
        },
        handleEnter(t) {
            if (t == 1) {
                this.$refs.searchArchivesRef[0].handleEnter();
            } else {
                this.$refs.searchArchivesRefName[0].handleEnter();
            }
        },
        closeArchives() {
            this.maskArchives = false;
            this.maskArchivesName = false;
        },
        // 拖动
        drag() {
            // 首先获取需要拖拽的dom节点
            const el1 = document.querySelectorAll('.dynamic-table-design .ant-table-tbody')[0];
            if (!el1) return false;
            // this.isDrag = true;
            Sortable.create(el1, {
                disabled: false, // 是否开启拖拽
                ghostClass: 'sortable-ghost', //拖拽样式
                animation: 150, // 拖拽延时，效果更好看
                group: { // 是否开启跨表拖拽
                    pull: false,
                    put: false
                },
                onEnd: (e) => { // 这里主要进行数据的处理，拖拽实际并不会改变绑定数据的顺序，这里需要自己做数据的顺序更改
                    let arr = this.dataSource; // 获取表数据

                    let removeItem = arr.splice(e.oldIndex, 1)[0];

                    arr.splice(e.newIndex, 0, removeItem); // 数据处理
                    //提前 赋值一个带值的数组（BUG 修复）
                    this.dataSource = [{}];
                    this.$nextTick(function () {
                        this.dataSource = [...arr];
                        this.dataSource.map((item, index) => {
                            item.sort = index + 1;
                        });
                    });
                }
            });
        },
        //下次进入方案保存
        inPagePlanSave(e) {
            if (e.target.checked) {
                this.defaultPlanActive = this.planActive;
                localStorage.setItem(this.reportCode, this.planActive);
            } else {
                this.defaultPlanActive = null;
                localStorage.setItem(this.reportCode, 0);
            }
        }
    }
}
</script>
<style lang="less">
.search-wrapper-box {
    // .ant-modal-content{
    //     transform:none !important;
    // }
    .ant-modal-close {
        z-index: 1;
    }
    .ant-modal-body {
        padding: 0;
    }
    .content-box {
        display: flex;
        height: 450px;
        .left-box {
            padding: 5px 0;
            flex: 0 0 200px;
            height: 100%;
            border-right: 1px solid #ccc;
            .plan-list {
                height: calc(100% - 36px);
                overflow-y: auto;
            }
            .plan-list ul {
                margin: 0;
                padding: 0;
            }
            .plan-list ul > li {
                list-style: none;
                width: 100%;
                padding-left: 10px;
                line-height: 32px;
                border-bottom: 1px solid #ccc;
                cursor: pointer;
                &.active {
                    background-color: #3788ff;
                    color: #fff;
                }
            }
            .plan-list ul > li:hover {
                background-color: rgba(55, 136, 255, 0.2);
                color: #666;
            }
            .plan-list ul > li:last-child {
                border-bottom: none;
            }
        }
        .right-box {
            padding: 2px 0;
            flex: 1;
            height: 100%;
            .condition {
                padding: 0 10px;
                margin-bottom: 10px;
                overflow-y: auto;
                .filter {
                    display: table;
                    margin-top: 10px;
                    .filter-label {
                        display: table-cell;
                        font-weight: normal;
                        max-width: 160px;
                        white-space: nowrap;
                        vertical-align: bottom;
                        text-overflow: ellipsis;
                        overflow: hidden;
                    }
                    .filter-control {
                        display: table-cell;
                        width: 100%;
                    }
                    .ant-select-selection--single {
                        height: auto;
                    }
                    .ant-input-number {
                        width: auto;
                    }
                    .ant-input,
                    .ant-input-number,
                    .ant-select-selection {
                        border-radius: 0;
                        border: none;
                        border-bottom: 1px solid #ccc;
                    }
                    .ant-input-number,
                    .ant-select-selection,
                    .ant-calendar-picker,
                    .ant-calendar-picker-input,
                    .ant-input:focus {
                        box-shadow: none;
                        height: 28px;
                    }
                    .ant-checkbox-wrapper {
                        font-weight: normal;
                    }
                    .ant-input-number-handler-wrap {
                        display: none;
                    }
                }
            }
            .dynamic-table-design {
                padding: 0 10px;
            }
        }
    }

    .btn-wrapper {
        // min-height: 52px;
        text-align: center;
        border-bottom: 1px solid #a0a0a0;
        .btns {
            font-size: 12px;
            cursor: pointer;
            overflow: hidden;
        }
        .btns-ccc {
            color: #ccc;
        }
        .btns-text {
            margin-top: -2px;
            height: 20px;
            overflow: hidden;
            .anticon-down {
                color: rgb(24, 144, 255);
                vertical-align: middle;
            }
        }
        .btns-icon {
            font-size: 22px;
            color: rgb(24, 144, 255);
        }
        .btns-icon-ccc {
            color: #ccc;
        }
        .btns:hover {
            .btns-icon {
                color: rgb(45, 85, 216);
            }
            transition: all 0.2s;
        }
        .btns:active {
            animation: btns-transform 0.1s cubic-bezier(0.36, 0.07, 0.19, 0.97)
                both;
        }
        //按钮制灰
        .btns-disable {
            color: #7f7d7d;
            .btns-icon {
                color: #7f7d7d;
            }
            .btns:hover {
                .btns-icon {
                    color: #7f7d7d;
                }
            }
            .btns-text {
                color: #7f7d7d;
                .anticon-down {
                    color: #7f7d7d;
                }
            }
        }
    }
    .mask-archives {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        // background: rgba(220, 53, 69, 0.5);
        background: rgba(0, 0, 0, 0);
        z-index: 2;
    }
    .mask-archives-name {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        // background: rgba(220, 53, 69, 0.5);
        background: rgba(0, 0, 0, 0);
        z-index: 4;
    }
    .mask-archives-type {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        // background: rgba(220, 53, 69, 0.5);
        background: rgba(0, 0, 0, 0);
        z-index: 5;
    }
}
</style>